package repository

import (
	"gorm.io/gorm"
	"shop-sys/model"
	"shop-sys/pkg/vo"
)

type ISysRoleMenuRepository interface {
	CreateRoleAndRoleMenu(*gorm.DB, uint, []uint) error
	DeleteBatch(*gorm.DB, string, []uint) error
	FindById(*gorm.DB, uint) ([]*model.SysRoleMenu, error)
	FindInRoleIdPerms(*gorm.DB, []uint) ([]*vo.SysRolePermsVO, error)
}

type sysRoleMenuRepository struct{}

func NewSysRoleMenuRepository() ISysRoleMenuRepository {
	return &sysRoleMenuRepository{}
}

/**
 * 根据角色id 批量添加角色与菜单关系
 * @param roleId
 * @param menuIdList
 */
func (rm *sysRoleMenuRepository) CreateRoleAndRoleMenu(db *gorm.DB, roleId uint, menuIdList []uint) error {
	var roleMenus []*model.SysRoleMenu

	for _, menuId := range menuIdList {
		r := model.SysRoleMenu{
			RoleId: roleId,
			MenuId: menuId,
		}
		roleMenus = append(roleMenus, &r)
	}

	return db.Create(roleMenus).Error
}

func (rm *sysRoleMenuRepository) DeleteBatch(db *gorm.DB, query string, Ids []uint) error {
	for _, id := range Ids {
		return db.Where(query, id).Delete(&model.SysRoleMenu{}).Error
	}
	return nil
}

func (rm *sysRoleMenuRepository) FindById(db *gorm.DB, roleId uint) (list []*model.SysRoleMenu, err error) {
	return list, db.Model(&model.SysRoleMenu{}).Where("role_id = ?", roleId).Find(&list).Error
}

func (rm *sysRoleMenuRepository) FindInRoleIdPerms(db *gorm.DB, roleIds []uint) (entityVOs []*vo.SysRolePermsVO, err error) {
	tx := db.Table("tz_sys_role_menu srm").
		Select([]string{"srm.menu_id, srm.role_id, sm.perms"}).
		Joins("LEFT JOIN tz_sys_menu sm ON srm.menu_id = sm.menu_id").
		Where("sm.type = 3").Where("sm.perms <> ?", "")
	if roleIds != nil && len(roleIds) > 0 {
		tx = tx.Where("srm.role_id in ?", roleIds)
	}
	return entityVOs, tx.Find(&entityVOs).Error
}